package br.unipar.lhmicheletti.controller;

import java.util.ArrayList;
import java.util.List;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;

import br.unipar.lhmicheletti.entity.Turma;
import br.unipar.lhmicheletti.manager.TurmaManager;

public class TurmaController {

	private Turma turma;
	
	@Autowired
	private TurmaManager turmaManager;
	
	public TurmaController(){
		this.turma = new Turma();
	}

	public List<Turma> getLista() {
		return turmaManager.buscarTodos();
	}

	public Turma getTurma() {
		return turma;
	}

	public void setTurma(Turma turma) {
		this.turma = turma;
	}
	
	public String salvar(){
		
		if ( "".equals( this.turma.getNome() ) ){
			return "INDEX";
		} else {
		    turmaManager.salvarTurma( this.turma );
		    //this.listaTurmas.add( this.turma );
		    this.turma = new Turma();
		    return "CADASTRO_TURMA";
		}
	}	
	
	public String excluir(){
		
		ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
		
		HttpServletRequest request = (HttpServletRequest)context.getRequest();
		
		String id = request.getParameter( "id" );
		
		System.out.println( "*********** TURMA:" + id );
		
		this.turma = turmaManager.buscarTurma( id );
		
		turmaManager.excluirTurma( this.turma );
				
		return "CADASTRO_TURMA";
	}
	
	public List<Turma> listagem( Object selecao ){
		List<Turma> listaTurmas = new ArrayList<Turma>();
		
		for (Turma turma : getLista() ) {
			if ( turma.getNome().contains( selecao.toString() ) ){
				listaTurmas.add( turma );
			}
		}
		
		return listaTurmas;
	}

}
